package com.uy.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.uy.system.model.entity.SysUser;
import com.uy.system.model.enums.HttpCode;
import com.uy.system.model.vo.LoginVo;
import com.uy.system.service.IAuthService;
import com.uy.system.service.ISysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author LY
 * @create 2024/3/25 11:55
 * @Description 认证服务
 */
@Service
public class AuthServiceImpl implements IAuthService {

    @Resource
    private ISysUserService iSysUserService;

    @Override
    public LoginVo doLogin(String username, String password) {
        SysUser sysUser = iSysUserService.findSysUser(username, password);
        // 登录
        StpUtil.login(sysUser.getUserId());
        String accessToken = StpUtil.getTokenValue();
        return LoginVo.builder()
                .tokenType("Bearer")
                .accessToken(accessToken)
                .build();
    }

    @Override
    public String logout() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Accesstoken");
        if (StrUtil.isBlank(token)) {
            return HttpCode.INVALID_TOKEN.getMsg();
        }
        StpUtil.logout();
        return null;
    }
}
